<template>
  <view class="nearby-shops-container">
    <view class="header">
      <view class="back-btn" @tap="navigateBack">
        <text class="back-icon">←</text>
      </view>
      <text class="title">附近门店</text>
      <view class="header-right">
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-container">
      <view class="search-box">
        <text class="search-icon">🔍</text>
        <input class="search-input" placeholder="搜索" v-model="searchQuery"
          @input="handleSearch"></input>
      </view>
    </view>

    <!-- 排序选项 -->
    <view class="sort-options">
      <view class="sort-item active">
        <text class="sort-text">综合排序</text>
      </view>
    </view>

    <!-- 门店列表 -->
    <view class="shops-list">
      <view class="shop-item" v-for="(shop, index) in filteredShops" :key="shop.id"
        @click="goToShopDetails(shop.id)">
        <view class="shop-info">
          <view class="shop-basic-info">
            <text class="shop-name">{{ shop.name }}</text>
            <text class="shop-distance">{{ shop.distance }}m</text>
          </view>
          <view class="shop-rating-reviews">
            <view class="rating">
              <text class="star">★★★★★</text>
              <text class="score">{{ shop.score }}</text>
            </view>
            <text class="reviews-count">评论：{{ shop.reviewsCount }}</text>
          </view>
          <view class="shop-details-info">
            <text class="business-hours">营业时间：{{ shop.businessHours }}</text>
            <text class="address">地址：{{ shop.address }}</text>
          </view>
        </view>
        <image class="shop-image" :src="shop.imageUrl" mode="aspectFill"></image>
      </view>
      <view class="no-more" v-if="filteredShops.length === 0">
        <text class="no-more-text">暂无更多</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'NearbyShops',
  data() {
    return {
      searchQuery: '',
      shopsData: [],
      loading: false
    }
  },
  computed: {
    filteredShops() {
      if (!this.searchQuery) {
        // 返回按星数降序排序的数据
        return [...this.shopsData].sort((a, b) => b.score - a.score)
      }
      const query = this.searchQuery.toLowerCase()
      // 搜索后也按星数降序排序
      return this.shopsData
        .filter(shop => 
          shop.name.toLowerCase().includes(query) || 
          shop.address.toLowerCase().includes(query)
        )
        .sort((a, b) => b.score - a.score)
    }
  },
  onLoad() {
    // 页面加载时获取门店数据
    this.fetchShopsData()
  },
  methods: {
    // 从接口获取门店数据
    fetchShopsData() {
      this.loading = true
      uni.request({
        url: 'http://localhost:8080/cc/merchant/list',
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 调整数据结构，适配页面显示需求
            this.shopsData = res.data.data.map(item => ({
              id: item.id.toString(),
              name: item.name,
              score: item.rate || 0, // 使用rate字段作为评分
              distance: this.calculateDistance(item.latitude, item.longitude), // 计算距离（实际应用中可能需要用户位置）
              reviewsCount: 0, // 初始化为0，后面会通过接口获取
              businessHours: this.formatBusinessHours(item.startTime, item.endTime), // 格式化营业时间
              address: item.address,
              imageUrl: '../../static/car-repair-shop.png' // 使用默认图片
            }))
            
            // 为每个门店获取评论数
            this.fetchAllReviewsCount()
          } else {
            console.error('获取门店数据失败:', res.data)
            uni.showToast({
              title: '获取门店数据失败',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          console.error('请求失败:', err)
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          })
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    
    // 为所有门店获取评论数
    fetchAllReviewsCount() {
      // 为每个门店获取评论数
      this.shopsData.forEach(shop => {
        this.fetchShopReviewsCount(shop.id)
      })
    },
    
    // 获取单个门店的评论数
    fetchShopReviewsCount(merchantId) {
      uni.request({
        url: `http://localhost:8080/cc/merchant/evaluateCount?merchantId=${merchantId}`,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 找到对应的门店并更新评论数
            const shopIndex = this.shopsData.findIndex(shop => shop.id === merchantId)
            if (shopIndex !== -1) {
              // 使用Vue的响应式更新方法
              this.$set(this.shopsData, shopIndex, {
                ...this.shopsData[shopIndex],
                reviewsCount: res.data.data || 0
              })
            }
          } else {
            console.error(`获取门店${merchantId}评论数失败:`, res.data)
          }
        },
        fail: (err) => {
          console.error(`请求门店${merchantId}评论数失败:`, err)
        }
      })
    },
    
    // 格式化营业时间
    formatBusinessHours(startTime, endTime) {
      // 假设startTime和endTime是如'08:00:00'和'21:00:00'这样的格式
      const start = startTime ? startTime.split(':').slice(0, 2).join(':') : '00:00'
      const end = endTime ? endTime.split(':').slice(0, 2).join(':') : '24:00'
      return `周一至周日 ${start}-${end}`
    },
    
    // 计算距离（这里使用模拟数据，实际应用中需要用户位置）
    calculateDistance(latitude, longitude) {
      // 模拟距离数据，实际应用中需要根据用户位置计算
      const distances = [300, 450, 600, 750, 900]
      return distances[Math.floor(Math.random() * distances.length)]
    },
    
    navigateBack() {
      uni.navigateBack()
    },
    
    handleSearch() {
      // 搜索逻辑已经通过computed属性实现
      console.log('搜索关键词:', this.searchQuery)
    },
    
    goToShopDetails(shopId) {
      // 添加日志以便调试
      console.log('跳转到门店详情页面，门店ID:', shopId);
      // 确保shopId存在且有效
      if (!shopId) {
        console.error('门店ID不存在或无效');
        return;
      }
      // 跳转到门店详情页面
      uni.navigateTo({
        url: '/pages/shop-details/shop-details?id=' + shopId,
        success: () => {
          console.log('页面跳转成功');
        },
        fail: (err) => {
          console.error('页面跳转失败:', err);
          uni.showToast({
            title: '跳转失败',
            icon: 'none'
          });
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.nearby-shops-container {
  background-color: #f8f8f8;
  min-height: 100vh;
}

.header {
  padding: 60rpx 0 30rpx 0;
  text-align: center;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.back-btn {
  position: absolute;
  left: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
  margin-top: 10px;
}

.back-icon {
  font-size: 40rpx;
  font-weight: bold;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin: auto;
}

.header-right {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
}

.more-icon {
  font-size: 32rpx;
}

/* 搜索框 */
.search-container {
  margin-top: 20rpx; /* 调整上边距，使页面内容不被挡住 */
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  padding: 15rpx 25rpx;
}

.search-icon {
  font-size: 28rpx;
  margin-right: 15rpx;
  color: #999;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  background-color: transparent;
}

.search-input::placeholder {
  color: #999;
}

/* 排序选项 */
.sort-options {
  display: flex;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 20rpx;
}

.sort-item {
  padding: 10rpx 20rpx;
  margin-right: 30rpx;
  position: relative;
}

.sort-item.active {
  color: #1677ff;
}

.sort-text {
  font-size: 28rpx;
}

.sort-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 20rpx;
  right: 20rpx;
  height: 4rpx;
  background-color: #1677ff;
  border-radius: 2rpx;
}

/* 门店列表 */
.shops-list {
  padding: 0 30rpx;
}

.shop-item {
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  padding: 25rpx;
  display: flex;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.shop-info {
  flex: 1;
  margin-right: 20rpx;
}

.shop-basic-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.shop-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.shop-distance {
  color: #1677ff;
  font-size: 26rpx;
  font-weight: bold;
  margin-left: 15rpx;
}

.shop-rating-reviews {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.rating {
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.star {
  color: #ffc107;
  font-size: 24rpx;
  margin-right: 8rpx;
}

.score {
  color: #666;
  font-size: 24rpx;
}

.reviews-count {
  color: #999;
  font-size: 24rpx;
}

.shop-details-info {
  font-size: 24rpx;
  color: #666;
}

.business-hours {
  display: block;
  margin-bottom: 5rpx;
}

.address {
  display: block;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.shop-image {
  width: 200rpx;
  height: 150rpx;
  border-radius: 10rpx;
}

.no-more {
  padding: 40rpx 0;
  text-align: center;
}

.no-more-text {
  color: #999;
  font-size: 28rpx;
}
</style>